import { getToken } from "./utils/auth";
import router from "./router";
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css' // 进度栏样式
import store from './store'
import { ElMessage } from "element-plus";
import { RouteRecordRaw } from "vue-router";
import { nextTick } from "vue";
NProgress.configure({ showSpinner: false }) //NProgress配置

const whiteList = ['/login']
router.beforeEach(async (to, from, next) => {
	NProgress.start()


	//1.判断用户是否已经登陆
	const hashToken = getToken()

	if (hashToken) {
		if (to.path === '/login') {
			next({ path: '/' })
		} else {
			const roles = store.getters.userInfo.roles
			if (roles) {
				next()
			} else {
				const { roles } = await store.dispatch('user/getInfo', getToken())
				const accessRoutes: Array<RouteRecordRaw> = await store.dispatch('permission/generateRoutes', roles)
				await accessRoutes.forEach((item: RouteRecordRaw) => {
					router.addRoute(item)
				})

				nextTick(() => {
					next({ path: to.path, replace: true })
				})
			}
		}
	} else {
		//未登录，进入白名单判断
		if (whiteList.indexOf(to.path) !== -1) {
			next()
		} else {
			ElMessage({ message: '请登录', type: 'warning' })
			next({ path: '/login' })
		}
	}

})

router.afterEach(() => {
	// 完成进度栏
	NProgress.done()
})